
package com.be.beadmin.device.impl;

import com.be.beadmin.common.entity.FilderExpressEntity;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.entity.SortExpressEntity;
import com.be.beadmin.device.dto.input.InspectTaskDto;
import com.be.beadmin.device.dto.output.*;
import com.be.beadmin.device.entity.*;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.device.mapper.*;
import com.be.beadmin.device.repository.InspectItemRepository;
import com.be.beadmin.device.repository.InspectPlanRepository;
import com.be.beadmin.device.repository.InspectSubItemRepository;
import com.be.beadmin.device.dto.output.InspectTaskEx;import com.be.beadmin.service.entity.InspectTask;
import com.be.beadmin.service.entity.InspectTask_;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.service.repository.InspectTaskRepository;
import com.be.beadmin.device.service.InspectTaskService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @description 服务实现
 * @author chenxu
 * @date 2023-08-03
 **/
@Service
@RequiredArgsConstructor
public class InspectTaskServiceImpl implements InspectTaskService {
    @Autowired
    private InspectPlanRepository inspectPlanRepository;
    @Autowired
    private com.be.beadmin.device.mapper.InspectPlanMapper InspectPlanMapper;
    @Autowired
    private InspectPlanMapperEx inspectPlanExMapper;
    @Autowired
    private  InspectTaskRepository inspectTaskRepository;
    @Autowired
    private  InspectTaskMapper inspectTaskMapper;
    @Autowired
    private  InspectTaskMapperEx inspectTaskExMapper;
    @Autowired
    private InspectItemRepository inspectItemRepository;
    @Autowired
    private InspectSubItemRepository inspectSubItemRepository;
    @Autowired
    private InspectSubItemMapper inspectSubItemMapper;
    @Autowired
    private InspectSubItemMapperEx inspectSubItemExMapper;

    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;

    @Autowired
    private NotifyTemplateInfoRepository notifyTemplateInfoRepository;

    @Autowired
    private NotifyInfoRepository notifyInfoRepository;

    @Override
    public Page<InspectTaskEx> getInspectTaskByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<InspectTask> page = inspectTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectTask_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectTask_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<InspectTaskEx> page1 = page.map(inspectTaskExMapper::toEntity);
        return page1;
//        Pageable pageable = PageRequest.of(
//                pageEntity.getCurrent() -1,
//                pageEntity.getPageSize());
//        Page<InspectPlan> page = inspectPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
//                    List<Predicate> list = new ArrayList<>();
//                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
//                    list.add(pre1);
//                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectPlan_.delete), 0); //过滤为0
//                    list.add(pre2);
//                    Predicate[] p = new Predicate[list.size()];
//                    List<Order> orders = new ArrayList<>();
//                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
//                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
//                        criteriaQuery.orderBy(orders);
//                    } else {
//                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectPlan_.createTime).as(Date.class)));
//                    }
//                    return  criteriaBuilder.and(list.toArray(p));
//                }
//                , pageable);
//            Page<InspectPlanEx> page1 = page.map(inspectPlanExMapper::toEntity);
//            List<InspectPlanEx> content = page1.getContent();
//            InspectTaskDto inspectTaskDto = new InspectTaskDto();
//            String[] times=null;
//            String period=null;
//            Date due=null;
//            Date creat=null;
//            int count=0;
//            if (content.size()==1)
//            {
//                for(InspectPlanEx map:content)
//                {
//                    if (map.getTimes()==null||map.getCreateTime()==null||map.getPeriod()==null||map.getDueTime()==null) {
//                        throw new BeadminException("生成失败,请检查该计划字段是否完整");
//                    }
//                    period=map.getPeriod();
//                    creat=map.getCreateTime();
//                    due=map.getDueTime();
//                    switch (map.getPeriod())
//                    {
//                        case "年":
//                        {
//                            String[] str=map.getTimes().split(",");
//                            List<Integer> month = new ArrayList<>();
//                            for(int j=0;j<str.length;j++)
//                            {
//                                month.add(Integer.valueOf(str[j].replace("月","").replace(" ","")));
//                                if(Integer.valueOf(str[j].replace("月",""))>12||Integer.valueOf(str[j].replace("月",""))<=0)
//                                {
//                                    throw new BeadminException("生成失败,输入数据不符合标准");
//                                }
//                            }
//                            int daysBetween =(int) Math.abs(due.getTime()-creat.getTime())/(24*60*60*1000);
//                            for(int i=0;i< month.size();i++) {
//
//                                for (int z=0;z<=daysBetween;z++) {
//                                    Calendar calendar =Calendar.getInstance();
//                                    calendar.setTime(creat);
//                                    calendar.add(Calendar.MONTH+1,1);
//                                    if (calendar.get(Calendar.MONTH+1)==month.get(i)) {
//                                        Calendar calendar1=Calendar.getInstance();
//                                        calendar1.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1,1);
//                                        inspectTaskDto.setTaskState("未完成");
//                                        inspectTaskDto.setInspectBy(map.getInspectBy());
//                                        inspectTaskDto.setTimeOut(false);
//                                        inspectTaskDto.setPlanedTime(calendar1.getTime());
//                                        inspectTaskDto.setCreateBy(map.getCreateBy());
//                                        inspectTaskDto.setInspectId(map.getInspectid());
//                                        addInspectTask(inspectTaskDto);
//                                    }
//                                }
//                            }
//                            break;
//                        }
//                        case "月":
//                        {
//                            String[] str=map.getTimes().split(",");
//                            List<Integer> day = new ArrayList<>();
//                            for(int j=0;j<str.length;j++)
//                            {
//                                day.add(Integer.valueOf(str[j].replace("日","").replace(" ","")));
//                                if(Integer.valueOf(str[j].replace("日",""))>31||Integer.valueOf(str[j].replace("月",""))<=0)
//                                {
//                                    throw new BeadminException("生成失败,输入数据不符合标准");
//                                }
//                            }
//                            int daysBetween =(int) Math.abs(due.getTime()-creat.getTime())/(24*60*60*1000);
//                            for(int i=0;i< day.size();i++)
//                            {
//                                for(int z=0;z<=daysBetween;z++)
//                                {
//                                    Calendar calendar =Calendar.getInstance();
//                                    calendar.setTime(creat);
//                                    calendar.add(Calendar.DAY_OF_MONTH,1);
//                                    if(calendar.get(Calendar.DAY_OF_MONTH)==day.get(i))
//                                    {
//                                        Calendar calendar1=Calendar.getInstance();
//                                        calendar1.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1,day.get(i));
//                                        inspectTaskDto.setTaskState("未完成");
//                                        inspectTaskDto.setInspectBy(map.getInspectBy());
//                                        inspectTaskDto.setTimeOut(false);
//                                        inspectTaskDto.setPlanedTime(calendar1.getTime());
//                                        inspectTaskDto.setCreateBy(map.getCreateBy());
//                                        inspectTaskDto.setInspectId(map.getInspectid());
//                                        addInspectTask(inspectTaskDto);
//                                    }
//                                }
//                            }
//                            break;
//                        }
//                        case "周": {
//                            String[] str = map.getTimes().split(",");
//                            List<Integer> week = new ArrayList<>();
//                            for (int j = 0; j < str.length; j++) {
//                                switch (str[j]){
//                                    case "星期一":
//                                    case "周一":
//                                        week.add(Calendar.MONDAY);
//                                        break;
//                                    case "星期二":
//                                    case "周二":
//                                        week.add(Calendar.TUESDAY);
//                                        break;
//                                    case "星期三":
//                                    case "周三":
//                                        week.add(Calendar.WEDNESDAY);
//                                        break;
//                                    case "星期四":
//                                    case "周四":
//                                        week.add(Calendar.THURSDAY);
//                                        break;
//                                    case "星期五":
//                                    case "周五":
//                                        week.add(Calendar.FRIDAY);
//                                        break;
//                                    case "星期六":
//                                    case "周六":
//                                        week.add(Calendar.SATURDAY);
//                                        break;
//                                    case "星期天":
//                                    case "周日":
//                                        week.add(Calendar.SUNDAY);
//                                        break;
//                                    default:
//                                        throw new BeadminException("生成失败,输入数据不符合标准");
//                                }
//                            }
//
//                                for (int i = 0; i < week.size(); i++) {
//                                    int daysBetween =(int) Math.abs(due.getTime()-creat.getTime())/(24*60*60*1000);
//                                    for(int z=0;z<=daysBetween;z++)
//                                    {
//                                        Calendar calendar =Calendar.getInstance();
//                                        calendar.setTime(creat);
//                                        calendar.add(Calendar.DAY_OF_MONTH,1);
//                                        if(calendar.get(Calendar.DAY_OF_WEEK)== week.get(i)){
//                                            Calendar calendar1=Calendar.getInstance();
//                                            calendar1.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DAY_OF_MONTH));
//                                            inspectTaskDto.setTaskState("未完成");
//                                            inspectTaskDto.setInspectBy(map.getInspectBy());
//                                            inspectTaskDto.setTimeOut(false);
//                                            inspectTaskDto.setPlanedTime(calendar1.getTime());
//                                            inspectTaskDto.setCreateBy(map.getCreateBy());
//                                            inspectTaskDto.setInspectId(map.getInspectid());
//                                            addInspectTask(inspectTaskDto);
//
//                                        }
//                                    }
//                                }
//
//                            break;
//                        }
//                        case "日":
//                        {
//                            String[] str=map.getTimes().split(",");
//                            List<Integer> hour = new ArrayList<>();
//                            for(int j=0;j<str.length;j++)
//                            {
//                                hour.add(Integer.valueOf(str[j].replace("点","").replace(" ","")));
//                                if(Integer.valueOf(str[j].replace("点",""))>24||Integer.valueOf(str[j].replace("点",""))<0)
//                                {
//                                    throw new BeadminException("生成失败,输入数据不符合标准");
//                                }
//                            }
//
//                            for (int i = 0; i < hour.size(); i++) {
//                                long daysBetween =Math.abs((long)due.getTime()-creat.getTime())/(24*60*60*1000);
//                                Calendar calendar =Calendar.getInstance();
//                                calendar.setTime(creat);
//                                for(int z=0;z<=daysBetween;z++)
//                                {
//                                    calendar.add(Calendar.DAY_OF_MONTH,1);
//                                    Calendar calendar1=Calendar.getInstance();
//                                    calendar1.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DAY_OF_MONTH),hour.get(i),0);
//                                    inspectTaskDto.setTaskState("未完成");
//                                    inspectTaskDto.setInspectBy(map.getInspectBy());
//                                    inspectTaskDto.setTimeOut(false);
//                                    inspectTaskDto.setPlanedTime(calendar1.getTime());
//                                    inspectTaskDto.setCreateBy(map.getCreateBy());
//                                    inspectTaskDto.setInspectId(map.getInspectid());
//                                    addInspectTask(inspectTaskDto);
//
//                                    }
//                                }
//                            }
//                            break;
//                        }
//
//                    }
//                }
//
//            else {
//                throw new BeadminException("生成失败,计划id不唯一");
//            }
//            InspectTask inspectTask = inspectTaskMapper.toEntity(inspectTaskDto);
//            inspectTaskRepository.save(inspectTask);

    }

    @Override
    public void addInspectTask(InspectTaskDto inspectTaskDto) {
        InspectTask result = inspectTaskRepository.findInspectTaskByIdAndDelete(inspectTaskDto.getId(), 0);
        if(ObjectUtil.isNotEmpty(result)) {
            throw new BeadminException("InspectTask不存在,请重新查询");
        }
        InspectTask inspectTask = inspectTaskMapper.toEntity(inspectTaskDto);
        inspectTaskRepository.save(inspectTask);
    }
//        Pageable pageable = PageRequest.of(
//                pageEntity.getCurrent() -1,
//                pageEntity.getPageSize());
//        Page<InspectPlan> page = inspectPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
//                    List<Predicate> list = new ArrayList<>();
//                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
//                    list.add(pre1);
//                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectPlan_.delete), 0); //过滤为0
//                    list.add(pre2);
//                    Predicate[] p = new Predicate[list.size()];
//                    List<Order> orders = new ArrayList<>();
//                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
//                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
//                        criteriaQuery.orderBy(orders);
//                    } else {
//                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectPlan_.createTime).as(Date.class)));
//                    }
//                    return  criteriaBuilder.and(list.toArray(p));
//                }
//                , pageable);
//        Page<InspectPlanEx> page1 = page.map(inspectPlanExMapper::toEntity);
//        InspectPlanEx inspectPlan=new InspectPlanEx();
//        for (InspectPlanEx inspectPlanEx : page1.getContent())
//        {
//            inspectPlan=inspectPlanEx;
//            break;
//
//        }
//        String time_series=inspectPlan.getTimes();
//        String period=inspectPlan.getPeriod();
//        Date due_time=inspectPlan.getDueTime();
//        Date new_time = new Date();
//        List<Date> times=getTimes(time_series,period,due_time,new_time);
//        InspectTaskDto inspectTaskDto=new InspectTaskDto();
//        inspectTaskDto.setInspectId(inspectPlan.getInspectID());
//        InspectTask inspectTask = inspectTaskMapper.toEntity(inspectTaskDto);
//        inspectTaskRepository.save(inspectTask);

    List<Date> getTimes(String time_series,String period,Date new_time,Date due_time)
    {

        List<Date> result = new ArrayList<>();

        String[] series = time_series.split(",");
        for (String s : series) {
            if (period.equals("年")) {
                result.addAll(getTimePeriodYearly(s, new_time, due_time));
            } else if (period.equals("月")) {
                result.addAll(getTimePeriodMonthly(s, new_time, due_time));
            } else if (period.equals("周")) {
                result.addAll(getTimePeriodWeekly(s, new_time, due_time));
            } else if (period.equals("日")) {
                result.addAll(getTimePeriodDaily(s, new_time, due_time));
            }
        }

        return result;
    }
    private static List<Date> getTimePeriodYearly(String targetMonth, Date newTime, Date dueTime) {
        List<Date> result = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Date currentDate = newTime;
        Map<String, Integer> monthMap = new HashMap<>();
        monthMap.put("一月", 0);  // 月份从0开始，所以一月对应0
        monthMap.put("二月", 1);
        monthMap.put("三月", 2);
        monthMap.put("四月", 3);
        monthMap.put("五月", 4);
        monthMap.put("六月", 5);
        monthMap.put("七月", 6);
        monthMap.put("八月", 7);
        monthMap.put("九月", 8);
        monthMap.put("十月", 9);
        monthMap.put("十一月", 10);
        monthMap.put("十二月", 11);

        calendar.setTime(currentDate);

        // Set the dueTime to midnight at the end of the day
        Calendar dueCalendar = Calendar.getInstance();
        dueCalendar.setTime(dueTime);
        dueCalendar.set(Calendar.HOUR_OF_DAY, 0);
        dueCalendar.set(Calendar.MINUTE, 0);
        dueCalendar.set(Calendar.SECOND, 0);
        dueCalendar.set(Calendar.MILLISECOND, 0);
        dueTime = dueCalendar.getTime();

        while (calendar.getTime().before(dueTime)) {
            int currentMonth = calendar.get(Calendar.MONTH);
            if (currentMonth == monthMap.get(targetMonth)) {
                // Set the current time to midnight at the beginning of the day
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                result.add(calendar.getTime());
            }
            if (currentMonth == Calendar.DECEMBER) {
                // If the current month is December, also increment the year
                calendar.add(Calendar.YEAR, 1);
                // Reset the month to the target month after incrementing the year
                calendar.set(Calendar.MONTH, monthMap.get(targetMonth));
                continue;
            }
            calendar.add(Calendar.MONTH, 1);


        }

        return result;
    }
    private static List<Date> getTimePeriodMonthly(String day, Date newTime, Date dueTime) {
        List<Date> result = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
            Date currentDate = newTime;
        Map<String, Integer> dayMap = new HashMap<>();
        dayMap.put("一日", 1);
        dayMap.put("二日", 2);
        dayMap.put("三日", 3);
        dayMap.put("四日", 4);
        dayMap.put("五日", 5);
        dayMap.put("六日", 6);
        dayMap.put("七日", 7);
        dayMap.put("八日", 8);
        dayMap.put("九日", 9);
        dayMap.put("十日", 10);
        dayMap.put("十一日", 11);
        dayMap.put("十二日", 12);
        dayMap.put("十三日", 13);
        dayMap.put("十四日", 14);
        dayMap.put("十五日", 15);
        dayMap.put("十六日", 16);
        dayMap.put("十七日", 17);
        dayMap.put("十八日", 18);
        dayMap.put("十九日", 19);
        dayMap.put("二十日", 20);
        dayMap.put("二十一日", 21);
        dayMap.put("二十二日", 22);
        dayMap.put("二十三日", 23);
        dayMap.put("二十四日", 24);
        dayMap.put("二十五日", 25);
        dayMap.put("二十六日", 26);
        dayMap.put("二十七日", 27);
        dayMap.put("二十八日", 28);
        dayMap.put("二十九日", 29);
        dayMap.put("三十日", 30);
        dayMap.put("三十一日", 31);
        while (calendar.getTime().before(dueTime) || calendar.getTime().equals(dueTime)) {
            int targetDay = dayMap.get(day); // 获取目标日期
            int currentMonth = calendar.get(Calendar.MONTH);
            int currentYear = calendar.get(Calendar.YEAR);

            // 检查当前月份是否包含目标日期
            Calendar tempCalendar = Calendar.getInstance();
            tempCalendar.set(Calendar.YEAR, currentYear);
            tempCalendar.set(Calendar.MONTH, currentMonth);
            tempCalendar.set(Calendar.DAY_OF_MONTH, targetDay);

            if (tempCalendar.get(Calendar.MONTH) == currentMonth && tempCalendar.getTime().before(dueTime)) {
                // 添加到result之前检查是否在开始时间之后
                if (!tempCalendar.getTime().before(newTime)) {
                    result.add(tempCalendar.getTime());
                }
            }

            // 将日期设置为下一个月的第一天
            calendar.add(Calendar.MONTH, 1);

            // 设置日期为目标日期
            calendar.set(Calendar.DAY_OF_MONTH, targetDay);

            // 如果设置后的日期仍然在当前月份，继续，否则回滚到上一个月
            if (calendar.get(Calendar.MONTH) != calendar.getTime().getMonth()) {
                calendar.add(Calendar.MONTH, -1);
                calendar.set(Calendar.DAY_OF_MONTH, targetDay);
            }
        }

        return result;




    }
    public static List<Date> getTimePeriodWeekly(String dayOfWeek, Date newTime, Date dueTime) {
        List<Date> result = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(newTime); // 设置初始日期
        int targetDayOfWeekValue = Calendar.SUNDAY; // 默认为周日，如果在 dayOfWeek 字符串中未指定

        switch (dayOfWeek) { // 将 dayOfWeek 字符串转换为对应的 Calendar 常量值
            case "周一": targetDayOfWeekValue = Calendar.MONDAY; break;
            case "周二": targetDayOfWeekValue = Calendar.TUESDAY; break;
            case "周三": targetDayOfWeekValue = Calendar.WEDNESDAY; break;
            case "周四": targetDayOfWeekValue = Calendar.THURSDAY; break;
            case "周五": targetDayOfWeekValue = Calendar.FRIDAY; break;
            case "周六": targetDayOfWeekValue = Calendar.SATURDAY; break;
        }

        while (calendar.getTime().before(dueTime)) {
            int currentYear = calendar.get(Calendar.YEAR);
            int currentMonth = calendar.get(Calendar.MONTH);

            // 寻找下一个目标星期几
            while (calendar.get(Calendar.DAY_OF_WEEK) != targetDayOfWeekValue) {
                calendar.add(Calendar.DATE, 1);
            }

            result.add(calendar.getTime()); // 将日期添加到结果列表中

            // 检查是否跨年或跨月
            if (calendar.get(Calendar.YEAR) != currentYear || calendar.get(Calendar.MONTH) != currentMonth) {
                // 如果跨年或跨月，重新设置日期为新时间的第一天
                calendar.setTime(newTime);
            } else {
                calendar.add(Calendar.DATE, 7); // 增加一周
            }
        }

        return result;
    }


    private static List<Date> getTimePeriodDaily(String hour, Date newTime, Date dueTime) {
            List<Date> result = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(newTime);

            Map<String, Integer> hourMap = new HashMap<>();
            hourMap.put("一点", 1);
            hourMap.put("二点", 2);
            hourMap.put("三点", 3);
            hourMap.put("四点", 4);
            hourMap.put("五点", 5);
            hourMap.put("六点", 6);
            hourMap.put("七点", 7);
            hourMap.put("八点", 8);
            hourMap.put("九点", 9);
            hourMap.put("十点", 10);
            hourMap.put("十一点", 11);
            hourMap.put("十二点", 12);
            hourMap.put("十三点", 13);
            hourMap.put("十四点", 14);
            hourMap.put("十五点", 15);
            hourMap.put("十六点", 16);
            hourMap.put("十七点", 17);
            hourMap.put("十八点", 18);
            hourMap.put("十九点", 19);
            hourMap.put("二十点", 20);
            hourMap.put("二十一点", 21);
            hourMap.put("二十二点", 22);
            hourMap.put("二十三点", 23);
            hourMap.put("二十四点", 24);

        int targetHour = hourMap.get(hour);
        Calendar targetCalendar = (Calendar) calendar.clone(); // 创建一个目标时间的副本
        int currentMonth = targetCalendar.get(Calendar.MONTH); // 当前月份
        int currentYear = targetCalendar.get(Calendar.YEAR); // 当前年份
        while (targetCalendar.getTime().before(dueTime)) {
            int currentHour = targetCalendar.get(Calendar.HOUR_OF_DAY);

            if (currentHour == targetHour && targetCalendar.getTime().before(dueTime)) {
                result.add(targetCalendar.getTime());
            }

            targetCalendar.add(Calendar.HOUR_OF_DAY, 1);

            // 处理跨月
            if (targetCalendar.get(Calendar.HOUR_OF_DAY) == targetHour) {
                if (targetCalendar.get(Calendar.MONTH) != currentMonth || targetCalendar.get(Calendar.YEAR) != currentYear) {
                    // 如果进入了下一个月份或年份，就更新currentMonth和currentYear
                    currentMonth = targetCalendar.get(Calendar.MONTH);
                    currentYear = targetCalendar.get(Calendar.YEAR);
                    targetCalendar.set(Calendar.DAY_OF_MONTH, 1); // 将日期设置为新月份的第一天
                }
            }
        }

        return result;



    }
    @Override
    public void updateInspectTask(InspectTaskDto inspectTaskDto) {
        InspectTask inspectTask = inspectTaskRepository.findInspectTaskById(inspectTaskDto.getId());
        inspectTask = inspectTaskMapper.toEntity(inspectTaskDto);
        inspectTaskRepository.save(inspectTask);
    }


    @Override
    public void delInspectTask(String id) {
        InspectTask inspectTask = inspectTaskRepository.findInspectTaskById(id);
        inspectTask.setDelete(1);
        inspectTaskRepository.save(inspectTask);
    }
    @Override
    public Page<InspectTaskEx> generateInspectTask(PageEntity pageEntity) {
        String times=null;
        String period=null;
        Date due_time=null;
        String TaskDesc=null;
        String InspectBy=null;
        String TaskState=null;
        String InspectID=null;

        //发消息用
        String inspectPlanId =null;
        Date senderTime = new Date();

        Page<InspectPlanEx> inspectplanpage=getInspectPlanByPage(pageEntity);
        for (InspectPlanEx inspectPlanEx : inspectplanpage.getContent()) {
            TaskDesc=inspectPlanEx.getInspectDesc();
            InspectBy=inspectPlanEx.getInspectBy();
            TaskState="未完成";
            InspectID=inspectPlanEx.getInspectID();
            times=inspectPlanEx.getTimes();
            period=inspectPlanEx.getPeriod();
            due_time=inspectPlanEx.getDueTime();

            //发消息用
            inspectPlanId = inspectPlanEx.getId();
        }
        //生成次数检查_________________
        PageEntity pageEntity1=new PageEntity();
        pageEntity1.setCurrent(1);
        pageEntity1.setPageSize(50);
        List<FilderExpressEntity> filters=new ArrayList<>();
        List<SortExpressEntity> sorters = new ArrayList<>();
        FilderExpressEntity filter = new FilderExpressEntity();
        filter.setField("inspectId");
        filter.setOperator("eq");
        filter.setValue(InspectID);
        filter.setAndOr("and");
        filters.add(filter);
        pageEntity1.setFilters(filters);
        pageEntity1.setSorters(sorters);
        Page<InspectTaskEx> flag_page=getInspectTaskByPage(pageEntity1);
        //---任务200次判断
        if(flag_page.getContent().size()>200)
        {
            return null;
        }
        //---任务200次判断
        for (InspectTaskEx flag_page1 : flag_page.getContent()) {
            if(Objects.equals(flag_page1.getTaskState(), "未完成"))
            {
                return null;
            }
        }

        //___________________________
        Date date = new Date();
        List<Date>  result=getTimes(times,period,date,due_time);
        int date_id=1;
        //---任务200次判断
        if(result.size()>200)
        {
            List<Date> limitresult=result;
            result=result.subList(0, 200);
        }
        //
//        System.out.println("result:"+result);
        for (Date datelist : result) {
            InspectTask inspectTask1=new InspectTask();
            inspectTask1.setTaskDesc(TaskDesc);
            inspectTask1.setInspectBy(InspectBy);
            inspectTask1.setTaskState(TaskState);
            inspectTask1.setInspectId(InspectID);
            inspectTask1.setPlanedTime(datelist);
            inspectTask1.setIsNotify(0);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String formattedDate = formatter.format(datelist);
            String TaskID="RW"+formattedDate+"."+date_id;
            inspectTask1.setTaskId(TaskID);
            date_id++;
            inspectTask1 = inspectTaskRepository.save(inspectTask1);
            generateInspectTask(TaskID,InspectID);

            //发消息用
            senderTime = inspectTask1.getCreateTime();
        }

        //-----------------------------------------------------------------------
        //发消息放最后
        //巡检计划的创建人  发给  巡检计划指定的巡检人InsepctBy，通知类型
        InspectPlan inspectPlan=inspectPlanRepository.findInspectPlanByIdAndDelete(inspectPlanId,0);
        if(inspectPlan!=null){
            //定义消息实体notifyInfo
            NotifyInfo notifyInfo =new NotifyInfo();
            notifyInfo.setModuleName("设备管理");
            notifyInfo.setFuncName("巡检计划");

            notifyInfo.setNotifyDesc("巡检计划编码为["+inspectPlan.getInspectID()+"],巡检任务已生成");
            notifyInfo.setNotifyType("通知");

            notifyInfo.setSenderName(inspectPlan.getCreateName());
            notifyInfo.setSenderId(inspectPlan.getCreateId());

            notifyInfo.setSendTime(senderTime);
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            //调用发消息的接口
            notifyTemplateInfoService.sendNotify(notifyInfo,-1,InspectBy,null);
        }

        //发消息放最后
        //-----------------------------------------------------------------------

        return null;
    }
    @Override
    public Page<InspectTaskEx> closeInspectTask(InspectTaskDto inspectTaskDto) {
        InspectTask inspectTask = inspectTaskRepository.findInspectTaskById(inspectTaskDto.getId());
        inspectTask = inspectTaskMapper.toEntity(inspectTaskDto);
        inspectTask.setTaskState("已完成");
        Date now = new Date();
        inspectTask.setFinishedTime(now);
        InspectTask inspectionTask = inspectTaskRepository.save(inspectTask);
        //-----------------------------------------------------------------------
        //发消息放最后
        //巡检计划的创建人  发给  巡检计划指定的巡检人InsepctBy，通知类型
        InspectPlan inspectPlan=inspectPlanRepository.findInspectPlanByIdAndDelete(inspectionTask.getInspectId(),0);
        if(inspectPlan!=null){
            //定义消息实体notifyInfo
            NotifyInfo notifyInfo =new NotifyInfo();
            notifyInfo.setModuleName("设备管理");
            notifyInfo.setFuncName("巡检计划");

            notifyInfo.setNotifyDesc("巡检单号为["+inspectionTask.getInspectId()+"],巡检任务号为[\"+inspectionTask.getTaskId()+\"],巡检任务已关闭");
            notifyInfo.setNotifyType("通知");

            notifyInfo.setSenderName(inspectPlan.getCreateName());
            notifyInfo.setSenderId(inspectPlan.getCreateId());

            notifyInfo.setSendTime(inspectionTask.getFinishedTime());
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            //调用发消息的接口
            notifyTemplateInfoService.sendNotify(notifyInfo,-1,inspectionTask.getInspectBy(),null);
        }

        //发消息放最后
        //-----------------------------------------------------------------------
    return null;
    }
    public void generateInspectTask(String TaskId,String InspectID)
    {
        PageEntity pageEntity=new PageEntity();
        pageEntity.setCurrent(1);
        pageEntity.setPageSize(50);
        List<FilderExpressEntity> filters=new ArrayList<>();
        List<SortExpressEntity> sorters = new ArrayList<>();
        FilderExpressEntity filter = new FilderExpressEntity();
        filter.setField("InspectID");
        filter.setOperator("eq");
        filter.setValue(InspectID);
        filter.setAndOr("and");
        filters.add(filter);
        pageEntity.setFilters(filters);
        pageEntity.setSorters(sorters);

        Page<InspectSubItemEx> inspectsubitembpage=getInspectSubItemByPage(pageEntity);
        for (InspectSubItemEx inspectsubitembpage1 : inspectsubitembpage.getContent()) {
            InspectItem inspectItem = new InspectItem();
            inspectItem.setItemName(inspectsubitembpage1.getCheckItem());
            inspectItem.setItemDesc(inspectsubitembpage1.getCheckDesc());
            inspectItem.setTaskId(TaskId);
            inspectItemRepository.save(inspectItem);
        }
    }

    public Page<InspectSubItemEx> getInspectSubItemByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<InspectSubItem> page = inspectSubItemRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectSubItem_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectSubItem_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<InspectSubItemEx> page1 = page.map(inspectSubItemExMapper::toEntity);
        return page1;

    }

    public Page<InspectPlanEx> getInspectPlanByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<InspectPlan> page = inspectPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectPlan_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectPlan_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<InspectPlanEx> page1 = page.map(inspectPlanExMapper::toEntity);
        return page1;

    }



    @Override
    public void delInspectTasks (List<String> ids) { }
}